<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="项目名称" size="small">
            <el-input v-model="searchForm.projectName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="合同编号" size="small">
            <el-input v-model="searchForm.contractCode"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="团队名称" size="small">
            <el-input v-model="searchForm.teamName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="发票号" size="small">
            <el-input v-model="searchForm.invoiceNumber"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <!--<el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>-->
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px" append-to-body>
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
          <el-form-item label="有无合同编号" size="small">
            <el-switch
              v-model="teamRow.isContractCode"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value=1
              :inactive-value=0
              :disabled="isProjectDisabled"
              @change="ContractCodeChange"
            >
            </el-switch>
          </el-form-item>
          <div v-if="teamRow.isContractCode">
            <el-form-item key="contractCode" prop="contractCode" label="合同编号" size="small">
              <el-autocomplete
                v-model="teamRow.contractCode"
                :fetch-suggestions="querySearchProject"
                @select="handleSelectProject"
                placeholder="请输入内容"
              >
              </el-autocomplete>
            </el-form-item>
            <el-form-item v-if="teamRow.projectName" label="合同项目" size="small">
              {{teamRow.projectName}}
            </el-form-item>
            <el-form-item v-if="teamRow.teamName" label="所属团队" size="small">
              {{teamRow.teamName}}
            </el-form-item>
            <el-form-item v-if="teamRow.address" label="项目地址" size="small">
              {{teamRow.address}}
            </el-form-item>
          </div>
          <div v-else>
            <el-form-item key="projectName" prop="projectName" label="合同项目" size="small">
              <el-input type="text" v-model="teamRow.projectName"></el-input>
            </el-form-item>
            <el-form-item key="teamName" prop="teamName" label="所属团队" size="small">
              <el-autocomplete
                v-model="teamRow.teamName"
                :fetch-suggestions="querySearchTeam"
                @select="handleSelectTeam"
                placeholder="请输入内容"
              >
              </el-autocomplete>
            </el-form-item>
          </div>
          <el-form-item prop="invoiceNumber" label="发票号" size="small">
            <el-input type="text" v-model="teamRow.invoiceNumber"></el-input>
          </el-form-item>
          <el-form-item prop="invoiceTitle" label="发票抬头" size="small">
            <el-input type="text" v-model="teamRow.invoiceTitle"></el-input>
          </el-form-item>
          <el-form-item prop="amount" label="发票金额" size="small">
            <el-input type="number" v-model.number="teamRow.amount">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <div v-if="teamRow.isContractCode">
            <el-row v-if="teamRow.invoiceType===10">
              <el-col class="other">
                <el-form-item v-if="teamRow.epcRate" label="开票税率" size="small">
                  {{teamRow.epcRate}}%
                </el-form-item>
              </el-col>
              <el-col class="other">
                <el-form-item v-if="teamRow.epcRate" label="开票税费" size="small">
                  {{Math.round(teamRow.epcRate * teamRow.amount /100*10000)/10000 || 0}}万元
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-else>
              <el-col class="other">
                <el-form-item v-if="teamRow.invoiceRate" label="开票税率" size="small">
                  {{teamRow.invoiceRate}}%
                </el-form-item>
              </el-col>
              <el-col class="other">
                <el-form-item v-if="teamRow.invoiceRate" label="开票税费" size="small">
                  {{Math.round(teamRow.invoiceRate * teamRow.amount /100*10000)/10000 || 0}}万元
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-else>
            <el-row>
              <el-col class="other">
                <el-form-item key="invoiceRate" prop="invoiceRate" label="开票税率" size="small" class="item-inline">
                  <el-select v-model="teamRow.invoiceRate" placeholder="请选择">
                    <el-option
                      v-for="item in global.invoiceRateList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col class="other">
                <el-form-item label="开票税费" size="small">
                  {{Math.round(teamRow.invoiceRate * teamRow.amount /100*10000)/10000 || 0}}万元
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-form-item prop="invoiceType" label="开票类型" size="small">
            <el-select v-model="teamRow.invoiceType" placeholder="请选择">
              <el-option
                v-for="item in global.invoiceList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="billUnit" label="开票单位" size="small">
            <el-select v-model="teamRow.billUnit" placeholder="请选择">
              <el-option
                v-for="item in global.billUnitList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="经办人" size="small">
            <el-autocomplete
              v-model="teamRow.operator"
              :fetch-suggestions="querySearchOperator"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item prop="invoiceTime" label="开票时间" size="small">
            <el-date-picker
              v-model="teamRow.invoiceTime"
              type="date"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <!--<div slot="footer" class="dialog-footer">-->
        <!--<el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>-->
        <!--<el-button size="small" @click="outerVisible = false">取消</el-button>-->
        <!--</div>-->
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="250">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.invoiceId)"
            type="text"
            size="small">
            查看
          </el-button>
          <!--
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
          -->
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    addProjectInvocie,
    deleteProjectInvocie,
    getProjectInvocieList,
    selectOperator,
    selectProjectInvocie,
    selectProjectName,
    updateProjectInvocie,
    selectTeam
  } from '@/api/invocie'
  import {
    getInvoiceList
  } from '@/api/pay'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const invoiceTime = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const invoiceType = function(row, column) {
    if (row.invoiceType) {
      let obj = {}
      obj = global.invoiceList.find((item) => {
        return item.value === row.invoiceType // 筛选出匹配数据
      })
      return obj.label
    }
  }

  const billUnit = function(row, column) {
    if (row.billUnit) {
      let obj = {}
      obj = global.billUnitList.find((item) => {
        return item.value === row.billUnit // 筛选出匹配数据
      })
      return obj.label
    }
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    props: ['dialogList', 'searchForm'],
    data() {
      return {
        colConfigs: [
          { prop: 'projectName', label: '项目名称', width: '150', fixed: true },
          { prop: 'contractCode', label: '合同编号', width: '150', fixed: true },
          { prop: 'teamName', label: '团队名称', width: '150' },
          { prop: 'invoiceNumber', label: '发票号', width: '150' },
          { prop: 'invoiceTitle', label: '发票抬头', width: '150' },
          { prop: 'amount', label: '开票金额(万元)', width: '100' },
          { prop: 'invoiceRate', label: '开票税率(%)', width: '100' },
          { prop: 'taxes', label: '开票税费(万元)', width: '100' },
          { prop: 'invoiceTime', label: '开票时间', width: '150', component: invoiceTime },
          { prop: 'invoiceType', label: '开票类型', width: '150', formatter: invoiceType },
          { prop: 'billUnit', label: '开票单位', width: '150', formatter: billUnit },
          { prop: 'operator', label: '经办人', width: '150' },
          { prop: 'address', label: '详细地址', width: '150' },
          { slot: 'opt' }
        ],
        searchFormList: {},
        costTypes: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增开票管理',
        marginTitle: '',
        marginType: 1,
        dialogType: 0,
        teamRow: {},
        teamRowClear: {
          contractCode: ''
        },
        margin: {},
        marginClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        marginVisible: false,
        pca: pca,
        rules: {
          contractCode: [
            { required: true, message: '请输入合同编号', trigger: 'change' }
          ],
          projectName: [
            { required: true, message: '请输入合同项目', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请输入所属团队', trigger: 'change' }
          ],
          invoiceNumber: [
            { required: true, message: '请输入开票号', trigger: 'change' }
          ],
          invoiceTitle: [
            { required: true, message: '请输入发票抬头', trigger: 'change' }
          ],
          amount: [
            { required: true, message: '请输入支出金额', trigger: 'change' }
          ],
          invoiceTime: [
            { required: true, message: '请选择开票时间', trigger: 'change' }
          ],
          invoiceType: [
            { required: true, message: '请选择开票类型', trigger: 'change' }
          ],
          billUnit: [
            { required: true, message: '请选择开票单位', trigger: 'change' }
          ],
          operator: [
            { required: true, message: '请输入经办人', trigger: 'change' }
          ]
        },
        visible: false,
        isProjectDisabled: false
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
    },
    computed: {
      global() {
        return global
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getInvoiceList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          console.log(this.tableData)
          this.listLoading = false
        })
      },
      provinceChange() {
        this.searchForm.cityId = ''
      },
      search() {
        this.pageNum = 1
        this.searchFormList = Object.assign({}, this.searchForm, this.dialogList)
        this.fetchData()
      },
      addTeam() {
        this.outerVisible = true
        this.isProjectDisabled = false
        this.dialogTitle = '新增开票管理'
        this.dialogType = 1
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.$set(this.teamRow, 'isContractCode', 1)
        this.$set(this.teamRow, 'invoiceType', 6)
        this.$set(this.teamRow, 'billUnit', 1)
        this.$set(this.teamRow, 'invoiceTime', '')
        this.$set(this.teamRow, 'amount', 0)
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
      },
      editTeam(invoiceId) {
        this.outerVisible = true
        this.isProjectDisabled = true
        this.dialogTitle = '查看开票管理'
        this.dialogType = 0
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          invoiceId: invoiceId
        }
        selectProjectInvocie(params).then(response => {
          this.teamRow = Object.assign({}, response.responseBody)
          this.$set(this.teamRow, 'isContractCode', this.teamRow.projectId ? 1 : 0)
          if (this.teamRow.invoiceType === 10) {
            this.teamRow.epcRate = this.teamRow.invoiceRate
          }
        })
      },
      editMargin(type, row) {
        this.marginVisible = true
        this.marginType = type
        this.marginTitle = type === 1 ? '打入保证金' : '退还保证金'
        this.margin = JSON.parse(JSON.stringify(this.marginClear))
        this.margin.depositId = row.depositId
      },
      submitForm(formName) {
        const params = {
          invoiceNumber: this.teamRow.invoiceNumber,
          invoiceTitle: this.teamRow.invoiceTitle,
          amount: this.teamRow.amount,
          invoiceType: this.teamRow.invoiceType,
          billUnit: this.teamRow.billUnit,
          operator: this.teamRow.operator,
          invoiceTime: this.teamRow.invoiceTime,
          remark: this.teamRow.remark ? this.teamRow.remark : ''
        }
        if (this.teamRow.isContractCode) {
          params.projectId = this.teamRow.projectId
          params.projectName = this.teamRow.projectName
          params.contractCode = this.teamRow.contractCode
          params.teamId = this.teamRow.teamId
          params.address = this.teamRow.address
          if (this.teamRow.invoiceType === 10) {
            params.invoiceRate = this.teamRow.epcRate
            params.taxes = Math.round(this.teamRow.epcRate * this.teamRow.amount / 100 * 10000) / 10000 || 0
          } else {
            params.invoiceRate = this.teamRow.invoiceRate
            params.taxes = Math.round(this.teamRow.invoiceRate * this.teamRow.amount / 100 * 10000) / 10000 || 0
          }
        } else {
          params.projectName = this.teamRow.projectName
          params.teamId = this.teamRow.teamId
          params.invoiceRate = this.teamRow.invoiceRate
          params.taxes = Math.round(this.teamRow.invoiceRate * this.teamRow.amount / 100 * 10000) / 10000 || 0
        }
        if (!this.dialogType) {
          params.invoiceId = this.teamRow.invoiceId
        }

        if (!this.teamRow.projectId && this.teamRow.isContractCode) {
          this.$message({
            message: '该项目不存在',
            type: 'warning'
          })
        } else if (!this.teamRow.teamId && !this.teamRow.isContractCode) {
          this.$message({
            message: '该团队不存在',
            type: 'warning'
          })
        } else {
          this.$refs[formName].validate((valid) => {
            console.log(valid)
            if (valid) {
              if (this.dialogType) {
                addProjectInvocie(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              } else {
                updateProjectInvocie(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        }
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          invoiceId: scope.row.invoiceId,
          teamId: scope.row.teamId,
          invoiceRate: scope.row.invoiceRate,
          isDel: 1
        }
        deleteProjectInvocie(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = this.teamRow.addressId[0]
        this.teamRow.cityId = this.teamRow.addressId[1]
        this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
      },
      ContractCodeChange() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.$set(this.teamRow, 'contractCode', '')
        this.$set(this.teamRow, 'projectName', '')
        this.$set(this.teamRow, 'address', '')
        this.$set(this.teamRow, 'teamName', '')
        this.$set(this.teamRow, 'operator', '')
        if (this.teamRow.isContractCode) {
          this.$set(this.teamRow, 'invoiceType', 6)
          this.$set(this.teamRow, 'invoiceRate', '')
        } else {
          this.$set(this.teamRow, 'invoiceType', 9)
          this.$set(this.teamRow, 'invoiceRate', 9)
        }
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.projectId
        if (queryString) {
          const params = {
            contractCode: queryString
          }
          selectProjectName(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.contractCode
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.$set(this.teamRow, 'projectId', item.projectId)
        this.$set(this.teamRow, 'projectName', item.projectName)
        this.$set(this.teamRow, 'contractCode', item.contractCode)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
        this.$set(this.teamRow, 'invoiceTitle', item.partyA)
        this.$set(this.teamRow, 'address', item.address)
        this.$set(this.teamRow, 'invoiceRate', item.invoiceRate)
        this.$set(this.teamRow, 'epcRate', item.epcRate)
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.teamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectTeam(item) {
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      querySearchOperator(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
          // teamId: this.teamRow.teamId,
            name: queryString
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.name
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      }
    },
    watch: {
      'dialogList': {
        handler(newValue, oldValue) {
          this.searchFormList = newValue
          this.fetchData()
        },
        immediate: true
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    height: calc(100vh - 300px);
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
